# -*- encoding: utf-8 -*-
"""

PyCharm 图像验证码操作
2024年10月25日11时50分
by wenyang

文件主要内容:


"""
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random

def main():
    def random_char():
        return chr(random.randint(65, 90))
    def random_color():
        return random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)
    def random_color2():
        return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)
    # 设置图片的宽度
    width = 60 * 4
    # 设置图片的高度
    height = 60
    # 创建Image对象 以及设置图片的大小和背景颜色
    image = Image.new('RGB', (width, height), (255, 255, 255))
    # 创建Font对象
    font = ImageFont.truetype("C:/Windows/Fonts/Arial.ttf", 36)
    # 创建Draw对象
    draw = ImageDraw.Draw(image)
    # 填充背景色
    for x in range(width):
        for y in range(height):
            draw.point((x, y), fill=random_color2())
    # 画干扰线 一共六条
    for i in range(6):
        # 根据两点画一条直线
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, height)
        y2 = random.randint(0, height)
        draw.line((x1, y1, x2, y2), fill=random_color())
    # 画验证码
    for i in range(4):
        draw.text((60 * i + 10, 10), random_char(), font=font, fill=random_color())
    # 模糊
    image = image.filter(ImageFilter.BLUR)
    # 展示图片
    image.show()
    # 保存图片
    image.save("./code.jpg", "jpeg")




if __name__ == "__main__":
    main()
